package com.practice.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreMain {

	public static void main(String[] args) {
		ExecutorService service = Executors.newCachedThreadPool();
		Semaphore position = new Semaphore(3);
		for (int i = 0; i < 10; i++) {
			service.submit(new SemaphoreCommand(i, position));
		}
		service.shutdown();
		position.acquireUninterruptibly(3);
		System.out.println("All work finished.");
		position.release(3);
	}

}

class SemaphoreCommand implements Runnable {
	private int id;
	private Semaphore position;

	public SemaphoreCommand(int i, Semaphore semaphore) {
		this.id = i;
		this.position = semaphore;
	}

	@Override
	public void run() {
		try {
			if (position.availablePermits() > 0) {
				System.out.println("Consumer [" + id
						+ "] enters, get available position.");
			} else {
				System.out.println("Consumer [" + id
						+ "] enters, not available position, wait");
			}
			position.acquire();
			System.out.println("Consumer [" + id + "] gets position");
			Thread.sleep((int) (Math.random() * 1000));
			System.out.println("Consumer [" + id + "] finished work");
			position.release();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
